package com.dounine.clouddisk360.parser.deserializer.authtoken;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.cookie.Cookie;

import com.alibaba.fastjson.JSON;
import com.dounine.clouddisk360.parser.AuthTokenParser;

public class AuthTokenResponseHandle implements ResponseHandler<AuthToken> {
	
	private AuthTokenParser authTokenParser;
	public AuthTokenResponseHandle(AuthTokenParser authTokenParser) {
		this.authTokenParser = authTokenParser;
	}

	@Override
	public AuthToken handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		List<Cookie> cookies = this.authTokenParser.getHttpClientContext().getCookieStore().getCookies();
		AuthToken authToken = this.desializer(cookies.stream().filter(c -> c.getName().equals(AuthTokenConst.COOKIE_NAME)).findFirst().get()
				.getValue());
		saveCookie();
		return authToken;
	}
	
	public String disassemblyResult(String result) {
		return String.format("{'token':'%s'}",result);
	}

	public AuthToken desializer(String result) {
		if (StringUtils.isNotBlank(result)) {
			result = disassemblyResult(result);
			return JSON.parseObject(result, AuthToken.class);
		}
		return null;
	}
	
	public void saveCookie(){
		authTokenParser.getCookieStoreUT().writeCookieStoreToDisk(
				authTokenParser.getConfig().getBasePath(), 
				authTokenParser.getHttpClientContext().getCookieStore(),
					AuthTokenConst.TOKEN_NAME, 
					true);
	}

}
